import axios from "axios";
import { message } from "../utils/index.js";

const instance = axios.create({
    baseURL: "http://localhost:81/api/v2",
    timeout: 10000, // Request timeout
})

instance.interceptors.response.use(resp => {
    if (resp.status !== 200 || resp.data.code !== 200) 
        message.error("请求错误：" + resp.data.msg || "请求错误");
    return resp.data;
}, error => {
    message.error("请求错误：" + resp.data.msg || "请求错误");
    return Promise.reject(error);
})

instance.defaults.headers['Authorization'] = localStorage.getItem('Authorization');

instance.setAuthorization = (token) => {
    if ( token ) {
        localStorage.setItem('Authorization', token);
        instance.defaults.headers['Authorization'] = token;
    } else {
        localStorage.removeItem('Authorization');
        delete instance.defaults.headers['Authorization'];
    }
}

export default instance;